from fastapi import APIRouter, UploadFile, File, HTTPException
from fastapi.responses import JSONResponse
import os
import uuid
from pathlib import Path
import io
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import sys
import logging
from app.config import COS_SECRET_ID, COS_SECRET_KEY, COS_REGION, COS_BUCKET, COS_DOMAIN

router = APIRouter()

# 配置日志
logging.basicConfig(level=logging.INFO, stream=sys.stdout)

# 创建本地上传目录（作为备份）
UPLOAD_DIR = Path(__file__).parent.parent / "static" / "uploads"
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)

# 初始化 COS 客户端
def get_cos_client():
    config = CosConfig(
        Region=COS_REGION,
        SecretId=COS_SECRET_ID,
        SecretKey=COS_SECRET_KEY
    )
    return CosS3Client(config)

@router.post("/upload/image")
async def upload_image(file: UploadFile = File(...)):
    """上传图片到腾讯云 COS"""
    try:
        # 检查文件类型
        if not file.content_type.startswith("image/"):
            raise HTTPException(status_code=400, detail="只能上传图片文件")
        
        # 读取文件内容
        file_content = await file.read()
        
        # 生成唯一文件名
        file_extension = os.path.splitext(file.filename)[1]
        unique_filename = f"{uuid.uuid4()}{file_extension}"
        
        # 保存到本地（可选，作为备份）
        file_path = UPLOAD_DIR / unique_filename
        with open(file_path, "wb") as f:
            f.write(file_content)
        
        # 上传到腾讯云 COS
        cos_client = get_cos_client()
        cos_key = f"article-images/{unique_filename}"
        
        # 使用内存流上传
        file_stream = io.BytesIO(file_content)
        response = cos_client.put_object(
            Bucket=COS_BUCKET,
            Body=file_stream,
            Key=cos_key,
            ContentType=file.content_type
        )
        
        # 构建图片 URL
        image_url = f"{COS_DOMAIN}/{cos_key}"
        
        # 返回符合 Vditor 要求的响应格式
        return {
            "code": 0,  # Vditor 需要 code=0 表示成功
            "data": {
                "errFiles": [],
                "succMap": {
                    file.filename: image_url
                }
            },
            "msg": "上传成功"
        }
    except Exception as e:
        logging.error(f"上传失败: {str(e)}")
        return JSONResponse(
            status_code=500,
            content={
                "code": 1,
                "msg": f"上传失败: {str(e)}"
            }
        ) 